<template>
	<section>
		<!--工具条 - 高级查询框-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="请输入关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="sn" label="标识" width="120" sortable>
			</el-table-column>
      <el-table-column prop="businessName" label="商机名" width="120" sortable>
      </el-table-column>
      <el-table-column prop="productName" label="产品名" width="120" sortable>
      </el-table-column>
      <el-table-column prop="price" label="金额" width="120" sortable>
      </el-table-column>
      <el-table-column prop="customerName" label="客户名" width="120" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" min-width="180" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.state == 0" style="color: green">待付款</span>
          <span v-if="scope.row.state == 1" style="color: yellow">已付定金</span>
          <span v-if="scope.row.state == 2" style="color: #50bfff">已付尾款</span>
          <span v-if="scope.row.state == 3" style="color: #50bfff">已完成</span>
          <span v-if="scope.row.state == -1" style="color: red">取消</span>
        </template>
      </el-table-column>
			<el-table-column label="操作">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
					<el-button v-if="scope.row.state == 1" type="danger" size="small" @click="handlePayDeposit(scope.$index, scope.row)">付尾款</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条 - 批量删除&分页条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination
          layout="prev, pager, next"
          :current-page="query.currentPage"
          @current-change="handleCurrentChange"
          :page-size="query.pageSize"
          :total="pageInfo.total"
          style="float:right;">
			</el-pagination>
		</el-col>

		<!--新增界面-->
		<el-dialog title="新增/修改" :visible.sync="depositFormVisible" :close-on-click-modal="false">
			<el-form :model="depositForm" label-width="80px" :rules="depositFormRules" ref="depositForm">
				<el-form-item label="名称" prop="name">
					<el-input v-model="depositForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="depositForm.state">
						<el-radio class="radio" :label="1">正常</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
        <el-form-item label="简介">
          <el-input type="textarea" v-model="depositForm.intro" auto-complete="off"></el-input>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="depositFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="save" :loading="depositFormLoading">提交</el-button>
			</div>
		</el-dialog>


    <el-dialog title="付尾款" :visible.sync="payDepositVisible" :close-on-click-modal="false">
      <el-form :model="payDepositData" label-width="80px" ref="depositActivity">
        <el-form-item label="产品名">
          <el-input v-model="payDepositData.productName" disabled auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="payDepositData.price" disabled auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="客户名">
          <el-input v-model="payDepositData.customerName" disabled auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="付款方式">
          <el-select v-model="payDepositData.payMethod" clearable value-key="id" placeholder="请选择">
            <el-option
                v-for="item in payModelList"
                :key="item.id"
                :label="item.title"
                :value="item">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="payDepositVisible = false">取消</el-button>
        <el-button type="primary" @click.native="depositPaySubmit" :loading="depositFormLoading">提交</el-button>
      </div>
    </el-dialog>

	</section>
</template>

<script>
	export default {
		data() {
			return {
				query:{
				  currentPage:1,  // 当前页
          pageSize:10,  // 每页显示条数
          keyword:""  // 关键字
        },
        pageInfo:{
				  total:0,
          rows:[]
        },
				listLoading: false,
				sels: [],//列表选中列
        
				depositFormVisible: false,//新增修改界面是否显示
				depositFormLoading: false,
				depositFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
        activitys:[],  // 营销活动数组
        employees:[],
				//新增修改界面数据
				depositForm: {
					id:null,
          fullName:"",
          phone:"",
          seller:{      // seller 营销人员
					  id:null
          }
				},
        depositActivityVisible:false,  // 控制线索关联活动弹框是否展示
        depositActivity:{
				   depositId:null,   // 线索id
           activityIds:[]   // 活动id
        },

        depositAssignVisible:false,
        productList:[],

        payModelList:[],
        payDepositVisible:false,
        payDepositData:{
				  depositId:null,
				  productName:"",
          price:null,
          customerName:"",
          payMethod:{
				    id:null,
            title:"",
            value:""
          }
        }
			}
		},
		methods: {
      depositPaySubmit(){
        console.log(this.payDepositData)
        this.$http.post("/deposit/pay",this.payDepositData)
            .then(result => {
              result = result.data;
              if(result.success){
                this.payDepositVisible = false;
                this.$message({message: '付尾款成功', type: 'success'});
                this.query.currentPage = 1;
                this.getDeposits();
              }else{
                this.$message({message: '付尾款失败!'+result.message, type: 'error'});
              }
            }).catch(result => {
          this.$message({message: '付尾款失败!'+result.message, type: 'error'});
        })
      },
      handlePayDeposit(index,row){
          this.payDepositData = {
            depositId:row.id,
            productName: row.productName,
            price: row.price,
            customerName: row.customerName,
            payMethod: {
              id: null
            }
          }
          this.payDepositVisible = true;
          // 查询付款方式
          this.$http.get("/dictionary/item/payModel")
                    .then(result => {
                      result = result.data;
                      if(result.success){
                        this.payModelList = result.result;
                      }else{
                        this.$message({message: '获取支付方式失败!'+result.message, type: 'error'});
                      }
                    }).catch(result => {
                        this.$message({message: '获取支付方式失败!'+result.message, type: 'error'});
                     })
      },
      changeBusinessSubmit(){
        console.log(this.businessData);
        this.$http.post("/deposit/business",this.businessData)
            .then(result => {
              result = result.data;
              if(result.success){
                this.businessVisible = false;
                this.$message({message: '转化商机成功', type: 'success'});
                this.query.currentPage = 1;
                this.getDeposits();
              }else{
                this.$message({message: '转化商机失败!'+result.message, type: 'error'});
              }
            }).catch(result => {
          this.$message({message: '转化商机失败!'+result.message, type: 'error'});
        })
      },
      handleChangeBusiness(){
        if(this.sels.length != 1){
          this.$message({message: '请选择一条线索后再进行操作', type: 'error'});
          return ;
        }
          // 弹框
        this.businessVisible = true;
        // 要给businessData中的deposit赋值,赋值为当前选中行的数据
        this.businessData.deposit = this.sels[0];
        // 查询所有的产品数据
        this.$http.get("/product")
            .then(result => {
              result = result.data;
              if(result.success){
                this.productList = result.result;
              }else{
                this.$message({message: '获取产品列表失败!'+result.message, type: 'error'});
              }
            }).catch(result => {
          this.$message({message: '获取产品列表失败!', type: 'error'});
        })
      },
      depositAssignSubmit(){
        this.$http.post("/deposit/assign",this.depositForm)
            .then(result => {
              result = result.data;
              if(result.success){
                this.depositAssignVisible = false;
                this.$message({message: '线索分配成功', type: 'success'});
                this.getDeposits();
              }else{
                this.$message({message: '线索分配失败!'+result.message, type: 'error'});
              }
            }).catch(result => {
          this.$message({message: '线索分配失败!'+result.message, type: 'error'});
        })
      },
      handleAssign(){
          // 点击分配之前要判断一下,是否选中线索,如果没有选中线索,要提示用户请选择, 如果一次选择了多个线索,也要提示用户:请选择一条线索后再进行分配
          if(this.sels.length != 1){
            this.$message({message: '请选择一条线索后再进行分配', type: 'error'});
            return ;
          }
          // this.sels 是选中的所有行的数据
          this.depositForm = this.sels[0];

          // 弹出一个框
          this.depositAssignVisible = true;
          // 查询出所有的员工,并赋值给营销人员下拉框
          this.getEmployeeList();
      },
      getEmployeeList(){
        this.$http.get("/employee")
            .then(result => {
              result = result.data;
              if(result.success){
                this.employees = result.result;
              }else{
                this.$message({message: '获取员工列表失败!'+result.message, type: 'error'});
              }
            }).catch(result => {
          this.$message({message: '获取员工列表失败!', type: 'error'});
        })
      },
      depositActivitySubmit(){
        console.log(this.depositActivity)
        // 调用后端的绑定活动的方法,将this.depositActivity传过去
        this.$http.post("/deposit/activity",this.depositActivity)
                  .then(result => {
                    result = result.data;
                    if(result.success){
                      this.depositActivityVisible = false;
                      this.$message({message: '添加活动成功', type: 'success'});
                    }else{
                      this.$message({message: '添加活动失败!'+result.message, type: 'error'});
                    }
                  }).catch(result => {
                     this.$message({message: '添加活动失败!'+result.message, type: 'error'});
                  })
      },
      handleDepositActivity(index,row){    // row是当前行数据
          // 弹框 - 线索绑定活动的弹窗
          this.depositActivityVisible = true;
          this.depositActivity.depositId = row.id;
          // 查询所有的营销活动,并且将查询出来的营销活动列表赋值给 this.activitys
          this.getActivitys();
      },
      getActivitys(){
        this.$http.get("/activity/legal")
            .then(result => {
              result = result.data;
              console.log(result)
              if(result.success){
                this.activitys = result.result;
              }else{
                this.$message({message: '获取活动列表失败!'+result.message, type: 'error'});
              }
            }).catch(result => {
          this.$message({message: '获取活动列表失败!', type: 'error'});
        })
      },
      search(){
        this.query.currentPage = 1;
        this.getDeposits();
      },
			handleCurrentChange(val) {  // val是当前页
				this.query.currentPage = val;
				this.getDeposits();
			},
			//获取部门列表
			getDeposits() {
				this.listLoading = true;  // 弹出加载框
				this.$http.post("/deposit",this.query)   // axios.defaults.baseURL+/deposit  http://localhost:80/api/deposit
                  .then(result => {
                    result = result.data; // result.data  {success:true,message:"",result:{total:1,rows:[]}}
                    console.log(result)
                    if(result.success){
                       this.pageInfo = result.result;
                       this.listLoading = false;  // 关闭加载框
                    }else{
                      this.$message({message: '查询分页失败!'+result.message, type: 'error'});
                    }
                  })
                  .catch(result => {
                    this.$message({message: "查询分页失败!", type: 'error'});
                  })
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					this.$http.delete("/deposit/"+row.id)
                    .then(result => {
                       result = result.data;
                       if(result.success){
                         this.$message({message: '删除成功', type: 'success'});
                         // 刷新列表
                         this.query.currentPage = 1;
                         this.getDeposits();
                         this.listLoading = false;  // 关闭弹出框
                       }else{
                         this.$message({message: '删除失败!'+result.message, type: 'error'});
                       }
                    })
				}).catch(() => {
          this.$message({message: '已取消删除', type: 'info'});
				});
			},


			//显示编辑界面
			handleEdit: function (index, row) {
				this.depositFormVisible = true;
				this.depositForm = Object.assign({}, row);
				if(this.depositForm.manager == null){
          this.depositForm.manager = {id:null}
        }
        if(row.path != null){
           let arrays = row.path.split("/");    // ['', '1', '2', '20'] 根据/分割之后,第一个位置是一个空字符串,是不需要的,另外最后一个值是当前部门的id,而不是父部门的id,所以也不需要
           let ids = [];
           for(let i=1;i<arrays.length-1;i++){
             ids.push(parseInt(arrays[i]))    // 数组分割之后里面的值都是字符串,而部门树的id都是数字,他们匹配不上就不能回显,因此需要parseInt()转一下
           }
          this.depositForm.parent = ids;
        }
        //this.depositForm.parent = [1,2];
        // 获取所有的员工数据
        this.getEmployeeList();
        // 获取部门树
        this.getDeptTree();
			},
			//显示新增界面
			handleAdd: function () {
				this.depositFormVisible = true;
				this.depositForm = {
          id:null,
          name:"",
          intro:"",
          manager:{
            id:null
          },
          parent:{
            id:null
          },
          path:"",
              state:null
        }
        // 获取所有的员工数据
        this.getEmployeeList();
        // 获取部门树
        this.getDeptTree();
			},
			//新增修改保存方法
			save: function () {
				this.$refs.depositForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.depositFormLoading = true;
							let para = Object.assign({}, this.depositForm);
							// 级联下拉框绑定后的值是数组,但是后端的parent需要的是一个对象,所以需要我们手动转一下
							if(para.parent != null){
							  let array = para.parent;
							  // 当用户选择多级部门以后,对于该部门而言,最后一个部门id才是它的父部门
                para.parent = {id:array[array.length-1]};
              }
							this.$http.put("/deposit",para)
                  .then(result => {
                      result = result.data;
                      if(result.success){
                        this.$message({message: '保存成功', type: 'success'});
                        this.depositFormLoading = false;
                        this.query.currentPage = 1;
                        this.getDeposits();
                        this.depositFormVisible = false;
                      }else{
                        this.$message({message: '保存失败!'+result.message, type: 'error'});
                      }
                  }).catch(result => {
                      this.$message({message: '保存失败!', type: 'error'});
                  })
						});
					}
				});
			},
			selsChange: function (sels) { // sels 就是这个表格中所有被选中的行的数据
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id).toString();
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = { ids: ids };
					batchRemoveUser(para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getDeposits();
					});
				}).catch(() => {

				});
			}
		},
		mounted() { 
			this.getDeposits();  // 做分页查询
		}
	}

</script>

<style scoped>

</style>